<template>
  <div>
    <div class="list-table mb10">
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <el-select v-model="queryParams.fundAccountId" size="mini" style="width: 150px; padding-bottom: 0px" @change="getSubjectList(queryParams.fundAccountId)">
          <el-option
            v-for="item in finFundAccountList"
            :key="item.id"
            :label="item.accountName"
            :value="item.id"
          />
        </el-select>
        {{ queryParams.yearMonth }}
      </el-form>
    </div>
    <div class="list-table">
      <!--    <div class="area-header">-->
      <!--      <span class="area-header-title">{{ $t("凭证列表") }}</span>-->
      <!--    </div>-->
      <div class="query">
        <el-popover
          v-model="visible"
          placement="bottom-start"
          width="500"
          trigger="click"
        >
          <div>
            <el-form ref="popoverForm" :model="form" :rules="rules" label-width="120px" class="dataForm">
              <el-row>
                <el-col :span="24">
                  <el-form-item :label="$t('会计期间')" prop="daterange">
                    <div class="flex-center">
                      <el-select v-model="form.startYearMonth" size="small" clearable :placeholder="$t('请选择')">
                        <el-option
                          v-for="item in finCarryoverRecordList"
                          :key="item.accountYearMonth"
                          :label="item.accountYearMonth"
                          :value="item.accountYearMonth"
                        />
                      </el-select>
                      至
                      <el-select v-model="form.endYearMonth" size="small" clearable :placeholder="$t('请选择')">
                        <el-option
                          v-for="item in finCarryoverRecordList"
                          :key="item.accountYearMonth"
                          :label="item.accountYearMonth"
                          :value="item.accountYearMonth"
                        />
                      </el-select>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('凭证字')" prop="voucherWordId">
                    <el-select v-model="form.voucherWordId" size="small" clearable :placeholder="$t('请选择')">
                      <el-option
                        v-for="item in finVoucherWordList"
                        :key="item.id"
                        :label="item.voucherWord"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('制单人')" prop="creator">
                    <UserSelect
                      v-model="form.creator"
                      size="small"
                      :placeholder="this.$t('制单人')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('摘要')" prop="abstractContent">
                    <el-input v-model="form.abstractContent" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" :placeholder="$t('摘要')" maxlength="2000" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('备注')" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" :placeholder="$t('备注')" maxlength="2000" />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item :label="$t('科目')" prop="subjectCode">
                    <el-select v-model="form.subjectCode" filterable size="small" clearable :placeholder="$t('请选择')">
                      <el-option
                        v-for="ele in fundAccountSubjectList"
                        :key="ele.subjectCode"
                        :label="ele.subjectCode + ' ' +ele.subjectName"
                        :value="ele.subjectCode"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item :label="$t('金额')" prop="money">
                    <div class="flex-center">
                      <Money v-model="form.moneyBegin" size="small" /> 至 <Money v-model="form.moneyEnd" size="small" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item :label="$t('凭证号')" prop="no">
                    <div class="flex-center">
                      <el-input v-model="form.accountNumStart" size="small" /> 至 <el-input v-model="form.accountNumEnd" size="small" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item :label="$t('排序依据')" prop="sortBy">
                    <el-radio-group v-model="form.sortBy">
                      <el-radio :label="0">凭证号排序</el-radio>
                      <el-radio :label="1">凭证日期排序</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item :label="$t('排序方式')" prop="sortType">
                    <el-radio-group v-model="form.sortType">
                      <el-radio :label="0">升序</el-radio>
                      <el-radio :label="1">降序</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <span class="query-footer">
              <el-button size="small" @click="visible = false">{{ $t('取消') }}</el-button>
              <el-button size="small" @click="resetQuery">{{ $t('重置') }}</el-button>
              <el-button type="primary" size="small" @click="queryHandle">{{ $t('确定') }}</el-button>
            </span>
          </div>
          <el-button slot="reference" type="primary" size="mini">{{ yearMonthLabel }}<i class="el-icon-arrow-down ml5" /></el-button>
        </el-popover>
        <div>
          <el-button size="mini" @click="uploadHandle">{{ $t("导入凭证") }}</el-button>
          <el-button size="mini" @click="exportVoucherHandle">{{ $t("导出凭证") }}</el-button>
          <el-button size="mini" @click="arrangeNumberHandle">{{ $t("整理断号") }}</el-button>
          <el-button :disabled="!(multipleSelection && multipleSelection.length > 0)" size="mini" @click="batchDeleteHandle">{{ $t("批量删除") }}</el-button>
        </div>
      </div>

      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="finAuxiliaryAccountingList"
        :default-expand-all="true"
        class="parentTable"
        height="calc(100vh - 260px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="expand" width="1px">
          <template slot-scope="props">
            <div class="el-expanded">
              <div class="conWrap">
                <div>日期：{{ parseTime(props.row.accountDate) }}<span class="ml10">凭证字号：{{ props.row.voucherWord + '-' + props.row.yearMonth + '-' + props.row.accountNum }}</span></div>
                <div class="action">
                  <span class="link-type" @click="insertHandle(props.row)">插入</span>
                  <span class="link-type" @click="deleteHandle(props.row)">删除</span>
                  <span class="link-type" @click="copyHandle(props.row)">复制</span>
                  <span class="link-type" @click="updateHandle(props.row)">修改</span>
                </div>
              </div>
              <el-table :data="props.row.detailList" :default-expand-all="true" :show-header="false" class="childTable">
                <el-table-column prop="index" width="41" />
                <el-table-column prop="abstractContent" align="left" label="摘要" min-width="250" />
                <el-table-column prop="subject" align="left" label="科目" min-width="400" />
                <el-table-column prop="borrowAmount" align="left" label="借方金额" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.borrowAmount ? moneyFormat(scope.row.borrowAmount) : '' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="loanAmount" align="left" label="贷方金额" width="350">
                  <template slot-scope="scope">
                    <span>{{ scope.row.loanAmount ? moneyFormat(scope.row.loanAmount) : '' }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="摘要" align="left" min-width="250" />
        <el-table-column label="科目" min-width="400" />
        <el-table-column label="借方金额" width="200" />
        <el-table-column label="贷方金额" width="350" />
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="form.pageNum"
        :limit.sync="form.pageSize"
        @pagination="getList"
      />
      <el-dialog v-el-drag-dialog title="凭证导出" :visible.sync="exportVoucherOpen" width="30%" :close-on-click-modal="false" :lock-scroll="false">
        <el-form ref="form" :model="exportVoucherForm" :rules="rules" label-width="120px" class="dataForm">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('导出选项')" prop="type">
                <el-radio-group v-model="exportVoucherForm.type">
                  <el-radio :label="0">导出全部凭证</el-radio>
                  <el-radio :label="1">导出选中凭证</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="exportVoucherOpen = false">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="exportVoucher">{{ $t('确定') }}</el-button>
        </span>
      </el-dialog>

      <el-dialog
        v-el-drag-dialog
        :title="$t('凭证')"
        :visible.sync="formOpen"
        width="70%"
        :close-on-click-modal="false"
        :lock-scroll="false"
        custom-class="dialogForm voucherDialog"
      >
        <voucherForm ref="voucherForm" :operate-type="operateType" />
      </el-dialog>

      <el-dialog
        title="上传"
        :visible.sync="upload.open"
        width="400px"
        :close-on-click-modal="false"
        :lock-scroll="false"
        append-to-body
      >
        <div v-loading="upload.loading">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :headers="upload.headers"
            :action="upload.url + '?fundAccountId=' + queryParams.fundAccountId + '&carryoverRecordId=' + queryParams.carryoverRecordId"
            :show-file-list="true"
            :disabled="upload.loading"
            :multiple="upload.multiple"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-exceed="handleFileExceed"
            :auto-upload="false"
            :file-list="upload.fileList"
            :accept="upload.accept"
            :before-upload="beforeUpload"
            style="color: #1890ff;"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              {{ $t('将文件拖到此处，或点击') }}
              <em>{{ $t('上传') }}</em>
              <p class="tip_phrase">仅允许导入"xls,xlsx"文件</p>
            </div>
            <div slot="tip" class="el-upload__tip">
              <el-link :underline="false" type="primary" style="font-size:14px;margin-top:10px" @click="fetchTemplate">
                {{ $t('下载Excel模板') }}
              </el-link>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <el-button size="small" @click="upload.open = false">{{ $t('取消') }}</el-button>
            <el-button size="small" type="primary" @click="submitFileForm">{{ $t('上传') }}</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import voucherForm from './voucherForm.vue'
import {
  arrangeVoucherNumber,
  batchDeleteAuxiliaryAccounting,
  delFinAuxiliaryAccounting,
  getAuxiliaryAccountList
} from '@/api/fin/auxiliaryAccounting/finAuxiliaryAccounting'
import { listFinVoucherWord } from '@/api/fin/voucherWord/finVoucherWord'
import { getFundAccountYearMonthList } from '@/api/fin/fundAccount/finFundAccount'
import { listFinCarryoverRecordAsc } from '@/api/fin/carryoverRecord/finCarryoverRecord'
import { getFundAccountSubjectList } from '@/api/fin/fundAccount/finFundAccountDetail'
import { getToken } from '@/utils/auth'
import { mapActions, mapState } from 'vuex'
export default {
  components: {
    voucherForm
  },
  data() {
    return {
      loading: false,
      total: 0,
      visible: false,
      exportVoucherOpen: false,
      formOpen: false,
      title: '2023年第12期',
      queryParams: {
        fundAccountId: undefined,
        carryoverRecordId: undefined,
        yearMonth: undefined,
        pageNum: 1,
        pageSize: 10
      },
      yearMonthLabel: undefined,
      operateType: 'insert',
      form: {
        fundAccountId: undefined,
        carryoverRecordId: undefined,
        yearMonth: undefined,
        startYearMonth: undefined,
        endYearMonth: undefined,
        voucherWordId: undefined,
        creator: undefined,
        abstractContent: undefined,
        remark: undefined,
        subjectCode: undefined,
        moneyBegin: undefined,
        moneyEnd: undefined,
        accountNumStart: undefined,
        accountNumEnd: undefined,
        sortBy: 0,
        sortType: 0,
        pageNum: 1,
        pageSize: 10
      },
      exportVoucherForm: {
        type: 0
      },
      rules: {},
      upload: {
        open: false,
        loading: false,
        fileList: [],
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/auxiliaryAccounting/finAuxiliaryAccounting/importData',
        accept: '.xls, .xlsx',
        multiple: false
      },
      finAuxiliaryAccountingList: [],
      finVoucherWordList: [],
      typeOptions: [],
      finFundAccountList: [],
      fundAccountSubjectList: [],
      finCarryoverRecordList: [],
      multipleSelection: []
    }
  },
  computed: {
    ...mapState('finReport', ['finQueryParams'])
  },
  created() {
    // 获取凭证字列表
    this.getVoucherWordList()
    this.getFundAccountList()
  },
  methods: {
    ...mapActions('finReport', ['changeQueryParams']),
    queryHandle() {
      this.visible = false
      this.yearMonthLabel = this.getYearMonthLabel(this.form.startYearMonth) + ' — ' + this.getYearMonthLabel(this.form.endYearMonth)
      this.getList()
    },
    getList() {
      this.loading = true
      this.form.fundAccountId = this.queryParams.fundAccountId
      getAuxiliaryAccountList(this.form).then(response => {
        this.finAuxiliaryAccountingList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getYearMonth(str) {
      return str.replace('年', '-').replace('月', '')
    },
    getYearMonthLabel(str) {
      if (str.indexOf('月') !== -1) {
        str.replace('-', '年')
      } else {
        return str.replace('-', '年') + '月'
      }
    },
    // 获取基金账套记录列表
    getFinCarryoverRecord(fundAccountId) {
      this.finCarryoverRecordList = []
      this.fundAccountSubjectList = []
      const param = {
        fundAccountId: fundAccountId
      }
      listFinCarryoverRecordAsc(param).then(response => {
        this.finCarryoverRecordList = response.rows
      })
      getFundAccountSubjectList(param).then(response => {
        this.fundAccountSubjectList = response.data
      })
      this.getList()
    },
    // 获取凭证字列表
    getVoucherWordList() {
      listFinVoucherWord({}).then(response => {
        this.finVoucherWordList = response.rows
      })
    },
    // 根据基金账套
    getSubjectList(fundAccountId) {
      if (fundAccountId === null || fundAccountId === undefined || fundAccountId === '') {
        return
      }
      if (this.finFundAccountList && this.finFundAccountList.length > 0) {
        this.finFundAccountList.forEach(item => {
          if (fundAccountId === item.id) {
            this.queryParams.carryoverRecordId = item.carryoverRecordId
            this.queryParams.yearMonth = item.yearMonth
            this.yearMonthLabel = item.yearMonth
            this.form.sortBy = 0
            this.form.sortType = 0
            this.form.startYearMonth = this.getYearMonth(item.yearMonth)
            this.form.endYearMonth = this.getYearMonth(item.yearMonth)
          }
        })
      }
      this.getFinCarryoverRecord(fundAccountId)
      const param = {
        fundAccountId: fundAccountId,
        yearMonth: this.queryParams.carryoverRecordId
      }
      console.log('param', param)
      this.changeQueryParams(param)
      this.$forceUpdate()
    },
    // 获取基金账套列表
    getFundAccountList() {
      this.finFundAccountList = []
      getFundAccountYearMonthList({}).then(response => {
        this.finFundAccountList = response.data
        if (this.finFundAccountList && this.finFundAccountList.length > 0) {
          const item = this.finFundAccountList[0]
          this.queryParams.fundAccountId = item.id
          this.queryParams.carryoverRecordId = item.carryoverRecordId
          this.queryParams.yearMonth = item.yearMonth
          if (this.finQueryParams.accountId && this.finQueryParams.yearMonth) {
            this.finFundAccountList.forEach(data => {
              if (data.id === this.finQueryParams.accountId) {
                this.queryParams.fundAccountId = data.id
                this.queryParams.carryoverRecordId = data.carryoverRecordId
                this.queryParams.yearMonth = data.yearMonth
                this.form.startYearMonth = this.getYearMonth(data.yearMonth)
                this.form.endYearMonth = this.getYearMonth(data.yearMonth)
                this.yearMonthLabel = this.getYearMonthLabel(this.form.startYearMonth) + ' — ' + this.getYearMonthLabel(this.form.endYearMonth)
              }
            })
          }
          this.yearMonthLabel = item.yearMonth
          this.form.startYearMonth = this.getYearMonth(item.yearMonth)
          this.form.endYearMonth = this.getYearMonth(item.yearMonth)
          this.form.sortBy = 0
          this.form.sortType = 0
          this.getFinCarryoverRecord(this.queryParams.fundAccountId)
        }
      })
    },
    // 删除按钮操作
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delFinAuxiliaryAccounting(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    // 凭证导出
    exportVoucherHandle() {
      this.exportVoucherOpen = true
    },
    // 批量删除
    batchDeleteHandle() {
      this.$confirm(this.$t('是否确认批量删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        console.log(this.multipleSelection, 'this.multipleSelection')
        const data = {
          idList: []
        }
        if (this.multipleSelection && this.multipleSelection.length > 0) {
          this.multipleSelection.forEach(item => {
            data.idList.push(item.id)
          })
        }
        console.log(data, 'data')
        return batchDeleteAuxiliaryAccounting(data)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    // 整理断号
    arrangeNumberHandle() {
      this.$confirm(this.$t('是否确认整理断号?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        return arrangeVoucherNumber(this.queryParams)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('断号整理成功'))
      }).catch(function() {
      })
    },
    // 删除按钮操作
    exportVoucher() {
      if (this.exportVoucherForm.type === 1) {
        if (!(this.multipleSelection && this.multipleSelection.length > 0)) {
          return this.msgInfo(this.$t('请先选择需要导出的凭证！'))
        }
      }
      // 0 导出全部，1导出选中
      const param = {
        type: this.exportVoucherForm.type,
        queryParams: this.form,
        multipleSelection: this.multipleSelection
      }
      this.downLoadExcelPost('/auxiliaryAccounting/finAuxiliaryAccounting/exportVoucher', param)
    },
    /** 修改按钮操作 */
    copyHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.voucherForm.copyInit(row)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.voucherForm.init(row)
      })
    },
    /** 插入按钮操作 */
    insertHandle(row) {
      if (this.queryParams.carryoverRecordId !== row.carryoverRecordId) {
        return this.msgWarning(this.$t('亲，已经结账的期间不能再添加凭证！'))
      } else {
        this.formOpen = true
        this.$nextTick(() => {
          // 调用form页面的 init 方法初始化数据
          row.operateHandle = 'insert'
          row.yearMonthStr = this.getYearMonthLabel(row.yearMonth)
          this.$refs.voucherForm.insertData(row)
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    resetQuery() {
      this.form = {
        startYearMonth: this.getYearMonth(this.queryParams.yearMonth),
        endYearMonth: this.getYearMonth(this.queryParams.yearMonth),
        voucherWordId: undefined,
        creator: undefined,
        abstractContent: undefined,
        remark: undefined,
        subjectCode: undefined,
        moneyBegin: undefined,
        moneyEnd: undefined,
        accountNumStart: undefined,
        accountNumEnd: undefined,
        sortBy: 0,
        sortType: 0
      }
      this.resetForm('popoverForm')
    },
    uploadHandle() {
      this.upload.open = true
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/凭证导入模板.xlsx'
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.upload.loading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('最多可上传1个文件'))
    },
    beforeUpload(file) {
      const fileType = file.type
      console.log('fileType', fileType)
      return true
    },
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
<style lang="scss" scoped>

/deep/.childTable {
  .el-table__header-wrapper {
    display: none;
  }
  &::before{
    background-color: transparent;
  }
}
/deep/.parentTable{
  >.el-table__body-wrapper>.el-table__body>tbody>.el-table__row.expanded>.el-table-column--selection{
    position: relative;
      >.cell{
        position: absolute;
        padding: 0;
        top: 18px;
        left: 10px;
      }
  }
}
.conWrap {
  height: 39px;
  background: #f0f0f0;
  line-height: 39px;
  padding-left: 10px;
  font-size: 13px;
  color: #7f7f7f;
  padding-left: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .action{
    display: flex;
    column-gap: 10px;
    padding-right: 10px;
    font-size: 13px;
  }
}

/deep/.el-table{
  &::before{
    background-color: transparent;
  }
  tbody{
    tr{
        td{
          border-bottom: 0;
        }
    }
  }
  .el-table__expand-column{
    width: 0px;
    .el-table__expand-icon{
      display: none;
    }
  }
  .el-table__header-wrapper {
    background: #ebebeb;
  }
  .has-gutter > tr > th {
    background: #ebebeb;
    font-size: 14px;
  }
}
/deep/.el-expanded{
  margin-top: -10px;
  border: 1px solid #f0f0f0;
  &:hover{
    box-shadow: 0 0 10px 0 #dadada;
    border-color: #dadada;
  }
}
.query{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}
.query-footer{
  text-align: right;
  display: block;
  margin-top: 10px;
}
.flex-center{
  display: flex;
  column-gap: 10px;
  align-items: center;
}
/deep/.el-dialog__body{
  .charge{
    padding-left: 0!important;
    padding-right: 0!important;
  }
  .charge-title{
    padding-top: 0!important;
  }
}
</style>
